new Vue({
    el: '#app',

    data: {
        ws: null, // Our websocket
        newMsg: '', // Holds new messages to be sent to the server
        chatContent: '', // A running list of chat messages displayed on the screen
        friendlist:'',//好友列表
        addtarget:'',//检测获取聊天记录表单的action变动
        target:'',//聊天焦点用户
        targetChange:false,//表示当前没有变更聊天焦点对象
        file_action:"http://localhost:8000/upload?type=file",//发送文件访问链接
        img_action:"http://localhost:8000/upload?type=img",//发送图片访问链接
        oldmsg_action:"http://localhost:8000/oldmsg",//查询历史消息访问链接
        addfriend_action:"http://localhost:8000/addfriend",
        password: null, // password address used for grabbing an avatar
        username: null, // Our username  
        addfriend_target_name :'',//添加好友        
        joined: false // True if password and username have been filled in
    },

    created: function() {
        var self = this;
        this.ws = new WebSocket('ws://' + window.location.host + '/ws');
        this.ws.addEventListener('message', function(e) {
            var msg = JSON.parse(e.data);     
            
            if(msg.type=="message"){
            	var sendtime=msg.sendtime;
                self.chatContent +='<p>'+sendtime+'</p>' 
                    +'<div class="chip">'
                    + '<img src="' + self.gravatarURL(msg.password) + '">' // Avatar
                    + msg.username
                + '</div>'
                + emojione.toImage(msg.message) + '<br/>'; // Parse emojis
            }else if(msg.type=="file"){
            	self.chatContent += '<div class="chip">'
                    + '<img src="' + self.gravatarURL(msg.password) + '">' // Avatar
                    + msg.username
                + '</div>'
                + '<a href="http://localhost:8000/download?filename='
                + msg.message
                + '">'
                +  msg.message
                + '</a><br/>'; // Parse emojis
            }else if(msg.type=="img"){
            	self.chatContent += '<div class="chip">'
                    + '<img src="' + self.gravatarURL(msg.password) + '">' // Avatar
                    + msg.username
                + '</div>'
                + '<img src="http://localhost:8000/img?filename='
                + msg.message
                + '"> </img><br/>'; // Parse emojis
               
            }else if(msg.type=="login_false"){
            	this.joined=false;
				alert(msg.message);
                location.reload();
				
            }else if(msg.type=="login_success"){
            	var getlist="";
            	getlist=msg.message.replace(/[\\]/g,'');
				self.friendlist=""
            	self.friendlist+=getlist;
				//self.friendlist=""//测试
				console.log("获取好友列表");				
            }else if(msg.type=="Addfriend_res"){            	
				alert(msg.message);  
            }



            var element = document.getElementById('chat-messages');
            element.scrollTop = element.scrollHeight; // Auto scroll to the bottom
        });
    },
    mounted(){window.vue = this},
    updated: function () {
         this.$nextTick(function () {
         // Code that will run only after the
         // entire view has been re-rendered
            if(this.targetChange==true){
        	    console.log("vue内部updated:"+"()"+"vue:"+vue.oldmsg_action);
	            console.log("html:"+$('#getOldMessageForm').attr('action'));
			    $('#getOldMessageForm').submit();
			    this.targetChange==false;			
            }          
         })
    },
    methods: {
        send: function () {
            if (this.newMsg != '') {
                this.ws.send(
                    JSON.stringify({
                        password: this.password,
                        username: this.username,
                        type:"message",
                        message: $('<p>').html(this.newMsg).text()+"[-]"+this.target, // Strip out html                        
                    }
                ));
                this.newMsg = ''; // Reset newMsg
            }
        },

        join: function () {
            if (!this.password) {
                Materialize.toast('You must enter an password', 2000);
                return
            }
            if (!this.username) {
                Materialize.toast('You must choose a username', 2000);
                return
            }
            this.password = $('<p>').html(this.password).text();
            this.username = $('<p>').html(this.username).text();
            //$('#selfname').attr("value")=$('<p>').html(this.username).text();
            this.joined = true;
            
            this.ws.send(
                    JSON.stringify({
                        password: this.password,
                        username: this.username,
                        message: $('<p>').html(this.newMsg).text(), // Strip out html
                        type:"login"
                    }
                ));
                this.newMsg = ''; // Reset newMsg
        },
        register: function () {
            if (!this.password) {
                Materialize.toast('You must enter an password', 2000);
                return
            }
            if (!this.username) {
                Materialize.toast('You must choose a username', 2000);
                return
            }
            this.password = $('<p>').html(this.password).text();
            this.username = $('<p>').html(this.username).text();
            this.joined = true;
            
            this.ws.send(
                    JSON.stringify({
                        password: this.password,
                        username: this.username,
                        message: $('<p>').html(this.newMsg).text(), // Strip out html
                        type:"register"
                    }
                ));
                this.newMsg = ''; // Reset newMsg
        },
        gravatarURL: function(password) {
            return 'http://www.gravatar.com/avatar/' + CryptoJS.MD5(password);
        },
        getUserName:function(){
        	return this.username;
			console.log("vue当前用户："+this.username);
        },        
        setTarget:function(uname){
        	var self = this;
        	this.target=uname;
			this.targetChange=true;
			self.chatContent="";			
			console.log("vue当前焦点："+this.target);			
        },        
        plusFileAction:function(add_url){
        	this.file_action="http://localhost:8000/upload?type=file";
        	this.file_action+=add_url;
			console.log("vue文件绑定action："+this.file_action);
        },
        plusImgAction:function(add_url){
        	this.img_action="http://localhost:8000/upload?type=img";
        	this.img_action+=add_url;
			console.log("vue图片绑定action："+this.img_action);
        },
        plusOldmsgAction:function(add_url){
        	this.oldmsg_action="http://localhost:8000/oldmsg"
        	this.oldmsg_action+=add_url;
			
			console.log("vue历史消息绑定action："+this.oldmsg_action);
        },
        plusAddFriendAction:function(add_url){
        	this.addfriend_action="http://localhost:8000/addfriend"
        	this.addfriend_action+=add_url;
			console.log("vue添加好友绑定action："+this.addfriend_action);					 
        },       
       
    },
   
});

function friend(target_name){    
    vue.setTarget(target_name);    
    $("#file_target").attr("value",target_name);
    $("#img_target").attr("value",target_name); 
    $("#oldmsg_target").attr("value",target_name); 
    log_username=vue.getUserName();
    vue.plusFileAction("&targetname="+target_name); 
    vue.plusImgAction("&targetname="+target_name); 
    var plus_oldmsg_url="?selfname="+log_username+"&targetname="+target_name;
    vue.plusOldmsgAction(plus_oldmsg_url);         
	console.log("当前焦点："+target_name+";户主名称："+log_username);
	//$('#getOldMessageForm').submit();
	testchange(1);
	$('#flushcon').attr('class',plus_oldmsg_url);
	testchange(2);
	//setTimeout(testchange(),2000);
 }
function nouse(){
	
}
function testchange(num){
	console.log(num+"()"+"vue:"+vue.oldmsg_action);
	console.log("html:"+$('#getOldMessageForm').attr('action'));
}
function addfriend(){
	log_username=vue.getUserName();	
	target_name=$("#addname").val();
	var plus_AddFriend_url="?selfname="+log_username+"&targetname="+target_name;
	vue.plusAddFriendAction(plus_AddFriend_url);	
}
var aSpan=document.getElementsByTagName("span");
var aDiv=document.getElementsByName("list");
var list=document.getElementsByTagName("a");
for (var i=0;i<aSpan.length;i++) {
    aSpan[i].index=i;
   
    //鼠标点击好友列表展现
    aSpan[i].onOff=true;
    aSpan[i].onclick=function(){
        //先让所有的好友列表隐藏、所有的好友大标题保持原先的样式
        for (var i=0;i<aSpan.length;i++) {
            aDiv[i].className="hidden";
            //aSpan[i].className="";
        }
        if(this.onOff){
            //箭头改为向下的
            this.className="act_show";
            //好友列表显示
            aDiv[this.index].className="show";
            aDiv[this.index]=document.getElementsByClassName("show");
            this.onOff=false;
        }else{
            //箭头颜色加深，鼠标移出恢复原貌
            this.className="act";
            //好友列表隐藏
            aDiv[this.index].className="hidden";
            aDiv[this.index]=document.getElementsByClassName("hidden");
            //所有的开关改为真
            //for (var i=0;i<aSpan.length;i++) {
                this.onOff=true;
            //}
            //清除所有好友列表的焦点
            //for (var i=0;i<list.length;i++) {
            //    list[i].className="";
            //}
        }
    }
}
 
//好友列表点击获得焦点
for (var i=0;i<list.length;i++) {
    list[i].onclick=function(){
        for (var i=0;i<list.length;i++) {
            list[i].className="";
        }
        this.className="act1";
    }
}
function timeFormat(date = 0, fmt = 'yyyy-MM-dd hh:mm:ss') {
    
    date = new Date(+date)
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + '';
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
      }
    }
    return fmt;
  }